﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;

namespace DCMS_Framework {
  public static class EnumUtils {

    public static string GetDescription( Enum enumType ) {
      string description = string.Empty;
      DescriptionAttribute da;

      FieldInfo fi = enumType.GetType( ).GetField( enumType.ToString( ) );
      da = ( DescriptionAttribute ) Attribute.GetCustomAttribute( fi, typeof( DescriptionAttribute ) );

      if ( da != null ) {
        description = da.Description;
      } else {
        description = enumType.ToString( );
      }
      return description;
    }


    public static T GetEnumForDescription<T>( string description )  {
      object returnValue = Activator.CreateInstance( typeof( T ) );
      Array enumArray = Enum.GetValues( typeof( T ) );
      foreach ( object obj in enumArray ) {
        string text = GetDescription( ( Enum ) obj );
        if ( text == description ) {
          returnValue = ( T ) obj;
        }
      }
      return ( T ) returnValue;
    }

  }
}
